/*******************************************************************************
 * Copyright (c) 2010 Eugene Vorobkalo.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Eugene Vorobkalo - initial API and implementation
 *     Andrey Fedorov
 ******************************************************************************/
package org.droidpres.activity;

import java.util.List;

import android.util.Log;
import android.widget.*;
import org.droidpres.R;
import org.droidpres.adapter.ProductListAdapter;
import org.droidpres.db.DB;
import org.droidpres.db.QueryHelper;
import org.droidpres.dialog.DocHead;
import org.droidpres.utils.Const;
import org.droidpres.utils.DocData;
import org.droidpres.utils.MenuItemInfo;
import org.droidpres.utils.Utils;
import org.droidpres.utils.onDocDataChange;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.inputmethod.InputMethodManager;

public class ProductListActivity extends AbsListActivity implements FilterQueryProvider,
		OnKeyListener, OnClickListener,	onDocDataChange {
	private static final int A_RESULT_QTY = 100;

	private static final int MENU_GROUP		= Menu.FIRST;
	private static final int MENU_SEARCH	= Menu.FIRST + 1;
	private static final int MENU_HEAD 		= Menu.FIRST + 2;
	private static final int MENU_CLEAN 	= Menu.FIRST + 3;
	private static final int MENU_SAVE	 	= Menu.FIRST + 4;

	private static final int DLG_QUERY_SAVE_DOCUMENT = 1;
	private static final int DLG_QUERY_STATE_DOCUMENT = 2;
	private static final int DLG_PRODUCT_GROUP = 3;
	//private static final int DLG_DOCHEAD = 4;

	private TextView mTvDocTotal;
	//private Bundle mActivityExtras;
	private MenuItem mMiSave;

	private boolean mFiltredFlag = false;
	private boolean mAvailableSaveFlag;

    private boolean mFlagInputOnlyProd = false;
    private long mDocId;
    private int mPriceId;

    private String mClientUID;
    private String mPriceUID;

	private float mOldQty = 1;

    private final String LOG_TAG = "ProdListActivity";

	public ProductListActivity() {
		super(R.layout.product_list, DB.TABLE_PRODUCT,
				new String[] {""},
				null);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {

        mDocId = 0;
        Bundle ActivityExtras;
        if ((ActivityExtras = getIntent().getExtras()) != null) {
            setTitle(ActivityExtras.getString(Const.EXTRA_DOC_PRICE_NAME)+ // TODO: Set left&right align title
                    " "+ActivityExtras.getString(Const.EXTRA_CLIENT_NAME));
            mFlagInputOnlyProd = (ActivityExtras.getInt(Const.EXTRA_PROD_INPUT_ONLY,0) == 1);
            mDocId = ActivityExtras.getLong(Const.EXTRA_DOC_ID, 0);
            mClientUID = ActivityExtras.getString(Const.EXTRA_CLIENT_UID);
            mPriceUID = ActivityExtras.getString(Const.EXTRA_PRICE_UID);
            mPriceId = ActivityExtras.getInt(Const.EXTRA_DOC_PRICE, 0);
        }else if(savedInstanceState != null) {
            // No intent is available =( trying getting data from savedInstance
            mFlagInputOnlyProd = savedInstanceState.getBoolean("flag_input_prod");
            mFiltredFlag = savedInstanceState.getBoolean("flag_filtered");
            mAvailableSaveFlag = savedInstanceState.getBoolean("flag_available_save");
            mDocId = savedInstanceState.getLong("doc_id");
            mClientUID = savedInstanceState.getString("client_uid");
            mPriceUID = savedInstanceState.getString("price_uid");
            mPriceId = savedInstanceState.getInt("price_id");
        } else{
            Toast.makeText(getBaseContext(), "Ошибка", 5).show();
            finish();
        }
        if(mPriceId == 0){
            Toast.makeText(getBaseContext(), "Ошибка:\n"+
                    "Выберите прайс!", 5).show();
            finish();
        }
        if(mDocId == 0){
            Toast.makeText(getBaseContext(), "Ошибка:\n"+
                    "В модуль ProductListActivity передан (id = 0)", 5).show();
            finish();
        }

        super.onCreate(savedInstanceState);


		mTvDocTotal = (TextView) findViewById(R.id.tvDocTotal);
		
		ProductListAdapter adp = (ProductListAdapter) mAdapter;
		if (savedInstanceState != null) { 
			adp.mDocData = savedInstanceState.getParcelable(
					Utils.getConstName(mAdapter.getClass(), "mDocData"));
		} else {
			adp.mDocData = new DocData();
		}
		adp.mDocData.setOnDocDataChange(this);
	    adp.mDocData.Load(mDocId, mDataBase);


		mAvailableSaveFlag = false;
		mAdapter.setFilterQueryProvider(this);

		getListView().setOnKeyListener(this);
		
		findViewById(R.id.tbProdInBox).setOnClickListener(this);
		findViewById(R.id.tbProdPresence).setOnClickListener(this);
        findViewById(R.id.tbProdSelected).setOnClickListener(this);

	}

	@Override
	protected CursorAdapter createAdapter(Cursor cursor) {
		return new ProductListAdapter(this,
				R.layout.product_list_item,
				cursor,
                new String[] {"name", "available", "price", "_id"}, 
                new int[] {R.id.tvDocGoods, R.id.tvDocAvilable, R.id.tvDocPrice, R.id.tvDocQty});
	}

	@Override
	protected Cursor createCursor() {
        mQueryHelper.appendFilter("active",QueryHelper.FILTER_AND,"tProd._active = 1");
        return mQueryHelper.CreateProductAndPricesCursor(mDataBase,mPriceId,mDocId);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_GROUP, Menu.NONE, R.string.lb_product_group).
		setIcon(android.R.drawable.ic_menu_directions);

		menu.add(0, MENU_SEARCH, Menu.NONE, R.string.lb_search).
		setIcon(android.R.drawable.ic_menu_search);

        if(!mFlagInputOnlyProd){
            menu.add(0, MENU_HEAD, Menu.NONE, R.string.lb_title_doc_params).
            setIcon(android.R.drawable.ic_menu_upload);
        }

		mMiSave = menu.add(0, MENU_SAVE, Menu.NONE, R.string.lb_save);
		mMiSave.setIcon(android.R.drawable.ic_menu_save);
		mMiSave.setEnabled(mAvailableSaveFlag);

		menu.add(0, MENU_CLEAN, Menu.NONE, R.string.lb_clean).
		setIcon(android.R.drawable.ic_menu_delete);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch  (item.getItemId()) {
		case (MENU_GROUP):
			showDialog(DLG_PRODUCT_GROUP);
			return true;
		case (MENU_SEARCH):
			InputMethodManager inputMgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			inputMgr.toggleSoftInput(0, 0);
			return true;
		//case (MENU_HEAD):
		//	showDialog(DLG_DOCHEAD);
		//	return true;
		case (MENU_CLEAN):
			((ProductListAdapter) mAdapter).mDocData.clear();
			mAdapter.notifyDataSetChanged();
			return true;
		case (MENU_SAVE):

            if(mFlagInputOnlyProd){
                SaveDocument(-1);
            }else{
                showDialog(DLG_QUERY_STATE_DOCUMENT);
            }

			return true;
		}
		return false;		
	}
	
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN &&
				mAvailableSaveFlag && !mFiltredFlag) {
			showDialog(DLG_QUERY_SAVE_DOCUMENT);
			return true;
		};
		if (keyCode == KeyEvent.KEYCODE_SEARCH && event.getAction() == KeyEvent.ACTION_DOWN) {
			InputMethodManager inputMgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			inputMgr.toggleSoftInput(0, 0);
			return true;
		}
		return false;
	}

	@Override
	protected void onListItemClick(ListView l, View v, int pos, long id) {
		super.onListItemClick(l, v, pos, id);

        Cursor cur = getCursor();

        ProductListAdapter adp = (ProductListAdapter) mAdapter;
		float _qty = adp.mDocData.getQty(id);
        float _casesize = QueryHelper.fieldByNameFloat(cur, "casesize");
        float _set_qty;

        if(!adp.mCaseShowFlag) _set_qty = (_qty > 0)?(_qty + mOldQty):mOldQty; // base unit
        else _set_qty = (_qty > 0)?(_qty + (mOldQty * _casesize)):(mOldQty * _casesize); // non base unit

        float _price = QueryHelper.fieldByNameFloat(cur, "price");
        float _price_manual = QueryHelper.fieldByNameFloat(cur, "doc_price");
	    ChangeQty(id, _set_qty, (_price_manual==0)?_price:_price_manual, 1);
	}

	@Override
	protected List<MenuItemInfo> createContextMenus(int position, long id) {
		Cursor cur = getCursor();
		ProductListAdapter adp = (ProductListAdapter) mAdapter; 
	
		cur.moveToPosition(position);
		float _casesize = QueryHelper.fieldByNameFloat(cur, "casesize");

        Intent intent = new Intent(this, InputQtyActivity.class);
		intent.putExtra(Const.EXTRA_PRODUCT_NAME, QueryHelper.fieldByNameString(cur, "name"));
		intent.putExtra(Const.EXTRA_PRODUCT_ID, id);

        float _price = QueryHelper.fieldByNameFloat(cur, "price");
        float _price_manual = QueryHelper.fieldByNameFloat(cur, "doc_price");
        intent.putExtra(Const.EXTRA_PRICE_STOCK, _price);
		intent.putExtra(Const.EXTRA_PRICE, (_price_manual==0)?_price:_price_manual);

		intent.putExtra(Const.EXTRA_CASESIZE, _casesize);
		
		float tqty = adp.mDocData.getQty(id);
		if (tqty > 0) {
			//if (adp.mCaseShowFlag && _casesize>0) {
			//	intent.putExtra(Const.EXTRA_QTY, tqty / _casesize);
			//} else {
				intent.putExtra(Const.EXTRA_QTY, tqty);
			//}
		}
		startActivityForResult(intent, A_RESULT_QTY);
		return null;
	}

	public void onClick(View v) {
        ProductListAdapter adp = (ProductListAdapter) mAdapter;
        switch (v.getId()) {
		case R.id.tbProdInBox:
			adp.mCaseShowFlag = ((ToggleButton)v).isChecked();
			if (adp.mCaseShowFlag) adp.nf = SetupRootActivity.getQtyFormat(this, getString(R.string.lb_qty_box));
			else adp.nf = SetupRootActivity.getQtyFormat(this, getString(R.string.lb_qty));
			adp.notifyDataSetChanged();
			break;
		case R.id.tbProdPresence:
			if (((ToggleButton)v).isChecked()) {
				mQueryHelper.appendFilter("QTY", QueryHelper.FILTER_AND, "available > 0");
			} else {
				mQueryHelper.removeFilter("QTY");
			}
			mAdapter.changeCursor(createCursor());
			break;
        case R.id.tbProdSelected:
            if (((ToggleButton)v).isChecked()) {
                ListAdapter adapter = getListView().getAdapter();
                String filterText = new String();
                for(int i = 0; i < adapter.getCount(); i++){
                    android.database.sqlite.SQLiteCursor cursor =(android.database.sqlite.SQLiteCursor)
                            adapter.getItem(i);
                    if (cursor.moveToFirst()) {
                        do {
                            float _qty = adp.mDocData.getQty(cursor.getLong(0));
                            if(_qty>0){
                                filterText=filterText+" OR tProd._id="+cursor.getLong(0);
                            }
                        } while (cursor.moveToNext());
                    }
                    cursor.close();
                }
                mQueryHelper.appendFilter("product_id", QueryHelper.FILTER_OR, "tProd._id = 0"+filterText);
            } else {
                mQueryHelper.removeFilter("product_id");
            }
            mAdapter.changeCursor(createCursor());
            break;
		}
	}

	public Cursor runQuery(CharSequence constraint) {
		String selection = constraint.toString().trim().toUpperCase();
		mFiltredFlag = (selection.length() > 0);
		if (mFiltredFlag) {
			selection = "name_case LIKE ('%" + selection + "%')";
			mQueryHelper.appendFilter("LIKE_NAME", QueryHelper.FILTER_AND, selection);
		} else 
			mQueryHelper.removeFilter("LIKE_NAME");
		return createCursor();
	}
	
	@Override
	protected Dialog onCreateDialog(int dialogID) {
		super.onCreateDialog(dialogID);
		
		switch (dialogID) {
		case DLG_QUERY_SAVE_DOCUMENT: //
			return new AlertDialog.Builder(this)
			.setTitle(android.R.string.dialog_alert_title)
			.setIcon(android.R.drawable.ic_dialog_alert)
			.setMessage(R.string.msg_SaveProductsToDocument)
			.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
			
				public void onClick(DialogInterface dialog,	int whichButton) {

                    if(mFlagInputOnlyProd){
                        SaveDocument(-1);
                    }else{
                        showDialog(DLG_QUERY_STATE_DOCUMENT);
                    }

                }
				
			})
			.setNegativeButton(R.string.no,  new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog,	int whichButton) {
				//	ProductListActivity.this.finish();
				}
			})
			.create();  // END:
		case DLG_QUERY_STATE_DOCUMENT: //
			return new AlertDialog.Builder(this).
			setTitle(R.string.lb_documents_status).
			setItems(R.array.itemDocState, new DialogInterface.OnClickListener() {
	
				public void onClick(DialogInterface dialog, int item) {
					SaveDocument(item);
				}
				
			}).create();
	
		case DLG_PRODUCT_GROUP: //

            //Cursor cursor = mDataBase.rawQuery("SELECT _id, name FROM " +
            //        DB.TABLE_PRODUCT_GROUP + "\n" +
            //        "WHERE uid in (SELECT DISTINCT productgroup_id FROM "+DB.TABLE_PRODUCT+") ORDER BY name", null);

            Cursor cursor = mDataBase.rawQuery("SELECT uid, name FROM " + DB.TABLE_PRODUCT_GROUP +
					" WHERE uid in (SELECT DISTINCT productgroup_uid FROM "+DB.TABLE_PRODUCT+") ORDER BY name", null);
	
			final CharSequence[] names = new CharSequence[cursor.getCount()+1];

            //final int[] ids = new int[cursor.getCount()+1];
			final String[] ids = new String[cursor.getCount()+1];

			names[0] = getString(R.string.lb_allproducts);
			ids[0] = "";
			
			int i = 1;
			if (cursor.moveToFirst())
				do {
					ids[i] = cursor.getString(0);
					names[i++] = cursor.getString(1);
				} while (cursor.moveToNext());
			cursor.close();
			
			Dialog dlg = new AlertDialog.Builder(this).
			setTitle(R.string.lb_product_group).
			setItems(names, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int item) {
					if (item > 0) {

                        /*
                        String group_uid = "'";
                        Cursor cur;
                        cur = mDataBase.rawQuery("SELECT uid FROM " + DB.TABLE_PRODUCT_GROUP + " WHERE _id="+ids[item], null);
                        if (cur.moveToFirst()) {
                            group_uid = cur.getString(0);
                        }
                        cur.close(); */

                        mQueryHelper.appendFilter("GR", QueryHelper.FILTER_AND, "productgroup_uid = '%s'", ids[item]);
						//mQueryHelper.appendFilter("GR", QueryHelper.FILTER_AND, "productgroup_id = '%s'", group_uid);

                        getListView().setFastScrollEnabled(false);
					} else {
						mQueryHelper.removeFilter("GR");
						getListView().setFastScrollEnabled(true);
					}
					
					mAdapter.changeCursor(createCursor());
				}
			}).create();
			return dlg;
	
		//case DLG_DOCHEAD:
		//	return new DocHead(this, new DialogInterface.OnClickListener() {
	    //
		//		public void onClick(DialogInterface dialog,	int whichButton) {
		//			if (whichButton == DialogInterface.BUTTON_POSITIVE) {
		//				mActivityExtras.putInt(Const.EXTRA_DOC_PRESVEN, ((DocHead) dialog).getPresVenType());
		//				mActivityExtras.putInt(Const.EXTRA_DOC_TYPE, ((DocHead) dialog).getDocTypeID());
		//				mActivityExtras.putString(Const.EXTRA_DOC_DESC, ((DocHead) dialog).getDocDesc());
		//			}
		//		}
		//
		//	});
			
		default:
			return null;
		}
	}

	/**
	 *
	@Override
	protected void onPrepareDialog(int dialogID, Dialog dialog) {
		super.onPrepareDialog(dialogID, dialog);
		switch (dialogID) {
		case DLG_DOCHEAD:
			((DocHead) dialog).setPresVenType(mActivityExtras.getInt(Const.EXTRA_DOC_PRESVEN));
			((DocHead) dialog).setDocTypeID(mActivityExtras.getInt(Const.EXTRA_DOC_TYPE));
			((DocHead) dialog).setDocDesc(mActivityExtras.getString(Const.EXTRA_DOC_DESC));
			
			((DocHead) dialog).setDocPriceText(mActivityExtras.getString(Const.EXTRA_DOC_PRICE_NAME));

			((DocHead) dialog).setDocPriceID(mActivityExtras.getInt(Const.EXTRA_DOC_PRICE, 0));

		}
	}
    */
    private void ChangeQty(long goosdsID, float qty, float price, float casesize) {
        ProductListAdapter adp = (ProductListAdapter) mAdapter;
        if (qty > 0) {
            if (casesize != 1.0) qty = qty * casesize;
            adp.mDocData.put(goosdsID, qty, price);
        } else {
            adp.mDocData.remove(goosdsID);
        }
        mAdapter.notifyDataSetChanged();
    }

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if (resultCode != RESULT_OK) return;
		
		switch (requestCode) {
		case A_RESULT_QTY:
            ProductListAdapter adp = (ProductListAdapter) mAdapter;
            float tqty = data.getFloatExtra(Const.EXTRA_QTY, 0);

            Log.d("ProdLsit_onResult","tqty="+tqty);

			ChangeQty(data.getLongExtra(Const.EXTRA_PRODUCT_ID, 0),
                    tqty,
					data.getFloatExtra(Const.EXTRA_PRICE, 0),
                    1);
                    //adp.mCaseShowFlag ? data.getFloatExtra(Const.EXTRA_CASESIZE, 0):(float)1.0);

            ////if (tqty > 0) mOldQty = tqty;
			break;
		}
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);

        Log.d(LOG_TAG, "onSaveInstanceState()==================");
        if(outState != null) {
            // Writing data to restore next time

            ProductListAdapter adp = (ProductListAdapter) mAdapter;
            outState.putParcelable(Utils.getConstName(mAdapter.getClass(), "mDocData"), adp.mDocData);

            outState.putBoolean("flag_filtered",mFiltredFlag);
            outState.putBoolean("flag_available_save",mAvailableSaveFlag);
            outState.putBoolean("flag_input_prod",mFlagInputOnlyProd);
            outState.putLong("doc_id", mDocId);
            outState.putString("client_uid", mClientUID);
            outState.putString("price_uid", mPriceUID);
            outState.putInt("price_id",mPriceId);
        }
	}


	public void onDataChange(float summ) {
		mTvDocTotal.setText(((ProductListAdapter) mAdapter).cf.format(summ));
		mAvailableSaveFlag = true;
		if (mMiSave != null) mMiSave.setEnabled(mAvailableSaveFlag);
	}

    public void butSave_Click(View v){
        SaveDocument(-1);
    }

	private void SaveDocument(int doc_state) {

        ProductListAdapter adp = (ProductListAdapter) mAdapter;

        ContentValues cval = new ContentValues();

        cval.put("number",      mDocId);
        cval.put("client_uid",   mClientUID);
        cval.put("pricelist_uid",mPriceUID);

        cval.put("itemcount", 	adp.mDocData.getQtySumm());
        cval.put("mainsumm", 	adp.mDocData.getSumm());
        if(doc_state != -1){
            cval.put("docstate", 	doc_state);
        }

        mDataBase.beginTransaction();

        mDataBase.update(DB.TABLE_DOCUMENT, cval, QueryHelper.KEY_ID + "=" + mDocId, null);
        mDataBase.delete(DB.TABLE_DOCUMENT_DET, "order_id = " + mDocId, null);

        adp.mDocData.Save(mDocId, mDataBase);

        mDataBase.setTransactionSuccessful();
        mDataBase.endTransaction();

        setResult(RESULT_OK, null);

		finish();
	}

}